package com.zhengxyou.jetpackdemo.work;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.zhengxyou.jetpackdemo.R;

import java.util.concurrent.TimeUnit;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.Constraints;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import static com.zhengxyou.jetpackdemo.work.AWorker.KEY_RESULT;

/**
 * 例子@see https://blog.csdn.net/guiying712/article/details/80386338
 */
public class WorkActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work);
        findViewById(R.id.btn_start_work).setOnClickListener(v -> startWork());
        findViewById(R.id.btn_start_money_work).setOnClickListener(v -> startMoneyWork());
    }

    private void startMoneyWork() {
        OneTimeWorkRequest workA = new OneTimeWorkRequest.Builder(AWorker.class).build();

//        Data data = new Data.Builder()
//                .putInt(KEY_X_ARG, 1)
//                .putString(KEY_Y_ARG, "KEY_Y_ARG")
//                .putLong(KEY_Z_ARG, 421)
//                .build();
//        OneTimeWorkRequest workB = new OneTimeWorkRequest.Builder(BWorker.class)
//                .setInputData(data)
//                .build();
//        WorkManager.getInstance().enqueue(workB);
        OneTimeWorkRequest workB = new OneTimeWorkRequest.Builder(BWorker.class).build();

        WorkManager.getInstance().beginWith(workA).then(workB).enqueue();

        WorkManager.getInstance().getWorkInfoByIdLiveData(workB.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        if (workInfo != null && workInfo.getState().isFinished()) {
                            String myResult = workInfo.getOutputData().getString(KEY_RESULT);
                            Log.e("TAG", myResult);
                        }
                    }
                });

        //链式任务
//        WorkManager.getInstance()
//                .beginWith(workA)
//                // Note: WorkManager.beginWith() returns a
//                // WorkContinuation object; the following calls are
//                // to WorkContinuation methods
//                .then(workB)    // FYI, then() returns a new WorkContinuation instance
//                .then(workC)
//                .enqueue();
//链式任务--并行多个任务
//        WorkManager.getInstance()
//                // First, run all the A tasks (in parallel):
//                .beginWith(Arrays.asList(workA1, workA2, workA3))
//                // ...when all A tasks are finished, run the single B task:
//                .then(workB)
//                // ...then run the C tasks (in any order):
//                .then(Arrays.asList(workC1, workC2))
//                .enqueue();

//        WorkContinuation chain1 = WorkManager.getInstance()
//                .beginWith(workA)
//                .then(workB);
//        WorkContinuation chain2 = WorkManager.getInstance()
//                .beginWith(workC)
//                .then(workD);
//        WorkContinuation chain3 = WorkContinuation
//                .combine(Arrays.asList(chain1, chain2))
//                .then(workE);
//        chain3.enqueue();


    }

    private void startWork() {

//        OneTimeWorkRequest
//        PeriodicWorkRequest
        Log.e("TAG", "WorkManager:——》" + android.os.Process.myPid() + "," + android.os.Process.myTid());

        Constraints constraints = new Constraints.Builder()
                .setRequiresBatteryNotLow(true)
                .setRequiresCharging(true)
                .build();

//        .setRequiredNetworkType(NetworkType.CONNECTED)  // 网络状态
//                .setRequiresBatteryNotLow(true)                 // 不在电量不足时执行
//                .setRequiresCharging(true)                      // 在充电时执行
//                .setRequiresStorageNotLow(true)                 // 不在存储容量不足时执行
//                .setRequiresDeviceIdle(true)                    // 在待机状态下执行，需要 API 23
//
//        https://www.jianshu.com/p/e495ee6e84de

        OneTimeWorkRequest compressionWork = new OneTimeWorkRequest
                .Builder(CompressWorker.class)
                .setConstraints(constraints)
                .addTag("cleanup")
                .build();

        WorkManager.getInstance().enqueue(compressionWork);

        WorkManager.getInstance().getWorkInfoByIdLiveData(compressionWork.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        if (workInfo != null && workInfo.getState().isFinished()) {
//                            Log.e("TAG", workInfo.getOutputData().getString("WORK"));
                            Log.e("TAG", workInfo.getId().toString());
                            Log.e("TAG", "WorkManager:——》" + android.os.Process.myPid() + "," + android.os.Process.myTid());
                        }
                    }
                });

//WorkManager尽最大努力取消任务，但这本质上是不确定的 - 当您尝试取消任务时，任务可能已经在运行或已完成。
// WorkManager还提供了以最大努力取消 唯一工作序列中的所有任务或具有指定标记的所有任务的方法。
//        WorkManager.getInstance().cancelWorkById(compressionWork.getId());
//        WorkManager.getInstance().cancelAllWorkByTag("cleanup");
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//            Log.e("TAG","PeriodicWorkRequest");
//            PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(CompressWorker.class, 300, TimeUnit.MILLISECONDS)
//                    .build();
//            WorkManager.getInstance().enqueue(periodicWorkRequest);
//        }

        Log.e("TAG", "PeriodicWorkRequest");
        //查看源码发发现最小15分钟
        PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(CompressWorker.class, 15, TimeUnit.MINUTES)
                .build();
        WorkManager.getInstance().enqueue(periodicWorkRequest);

        WorkManager.getInstance().getWorkInfoByIdLiveData(periodicWorkRequest.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        Log.e("TAG", "============");
                        Log.e("TAG", "periodicWorkRequest:——》" + android.os.Process.myPid() + "," + android.os.Process.myTid());

                        if (workInfo != null && workInfo.getState().isFinished()) {
//                            Log.e("TAG", workInfo.getOutputData().getString("WORK"));
                            Log.e("TAG", workInfo.getId().toString());
                            Log.e("TAG", "periodicWorkRequest:——》" + android.os.Process.myPid() + "," + android.os.Process.myTid());
                        }
                    }
                });
    }


    public static void start(Context context) {
        Intent starter = new Intent(context, WorkActivity.class);
        context.startActivity(starter);
    }
}
